let messageCallback = null;
let socket = null;
function websocketonmessageCall (e) {
    messageCallback(JSON.parse(e.data))
}


export function initWebSocket() { //初始化weosocket
    const wsuri = process.env.VUE_APP_WS_URL+"chat";
    socket= new WebSocket(wsuri);
    socket.onmessage = websocketonmessage;
    socket.onopen = websocketonopen;
    socket.onerror = websocketonerror;
    socket.onclose = websocketclose;
    socket.onmessage=websocketonmessage;
}

function websocketonopen(Data) { //连接建立之后执行send方法发送数据
    //websocketsend("{}");
    console.log("websocket 链接",Data);
}

function websocketonerror(e) {//连接建立失败重连
    console.log("websocket 链接 发生错误",e);
    //initWebSocket();
}

function websocketonmessage(e) { //数据接收
    websocketonmessageCall(e);
}
export function websocketsend(Data) {//数据发送
    let str = JSON.stringify(Data);

    console.log("socket",socket)
    if (socket==null){
        initWebSocket();
    }
    console.log("socket2",socket)
    if (socket.readyState === 3) {
        socket.close();
        initWebSocket() // 重连
    }
    if (socket.readyState === 1) {
        socket.send(str);
    } else if (socket.readyState === 0) {
        setTimeout(() => {
            socket.send(str)
        }, 3000)
    }
}
function websocketclose(e) {  //关闭
    console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
    console.log('断开连接', e);
    if (e.code===1006){//重连
        initWebSocket();
    }
}

export function sendWebsocket (successCallback) {
    messageCallback = successCallback;
}
